package com.qf.netty.handler;

import com.alibaba.fastjson.JSON;
import com.qf.netty.entity.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * WebSocket文本帧的处理器
 * author Ken
 * create_time 2023/1/4
 */
@Slf4j
public class TextFrameChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("[client init] 有一个新的客户端连接了服务器！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.error("[client close] 有一个客户端断开了服务器的连接！");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String content = msg.text();
        log.info("[ws text frame] 接收到客户端的消息：{}", content);

        //将客户端消息的json，转换成实体对象，再往后传递
        Message message = JSON.parseObject(content, Message.class);
        ctx.fireChannelRead(message);
    }
}
